<template>
    <div class="storelist_container">
        <ZWGroup ref="GroupingRef" type="22" :group-id="group_id" :auth-code="authCode" @submit="handleGroupSubmit" />
        <!-- type=22门店列表 -->
        <div class="storelist_main">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="expandHandle" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                :close-loading="true"
                @select="onSelect"
                @selection-change="onSelectionChange"
                @select-all="onSelectAll">
                <template #headerOperate>
                    <el-button v-auth="'BATCH_CLOSE'" :disabled="!checkList.length" @click="onChange(3)">
                        批量关店
                    </el-button>
                    <el-button v-auth="'BATCH_OPEN'" :disabled="!checkList.length" @click="onChange(4)">
                        批量开店
                    </el-button>
                    <el-button v-auth="'BATCH_DEL'" :disabled="!checkList.length" @click="onChange(6)">
                        批量下载
                    </el-button>
                    <el-button v-auth="'EXPORT_MD'" @click="ImportStore()">导入门店</el-button>
                    <el-button v-auth="'ADD_RULE'" type="primary" @click="getNewStore">新建门店</el-button>
                </template>
            </ZwTable>
        </div>
    </div>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
    <!-- 录入客户 -->
    <ImportCustomer
        ref="ImportCustomerRef"
        :selectid="group_id"
        @cancel="closeImportCustomer"
        @save="onImportCustomer" />
    <!-- 门店员工  -->
    <ZWDrawer ref="DetailedRef" @close="showBox">
        <detailed :id="cus_import_id" :key="cus_import_id" />
    </ZWDrawer>
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import {
    getStogeDownload,
    getSensitivelist,
    getStogeChange1,
    getStogeDel
} from '@/api/employe/storemanagement/sensitiveWord';
import { getCreateList } from '@/api/common';
import ImportCustomer from './components/ImportCustomer.vue';
import detailed from './components/detailed.vue';
import { ref, reactive, computed, onActivated, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { useStore } from '@/store';
import { downFile } from '@/utils/utils';
import { endLoading, startLoading } from '@/utils/request';
const store = useStore();
const DeletdialogRef: any = ref(null);
const ImportCustomerRef: any = ref(null);
const DetailedRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const GroupingRef: any = ref(null);
const isShow = ref(0);
const checkList = ref([]);
const delId = ref([]);
const cus_import_id = ref('');
const group_id = ref<string>('all');
const defaultParams = {
    group_id: 'all',
    search_value: '', //活动标题
    created_id: [], //创建人id
    store_status: -1, //活动状态 -1-全部 1-开启 2-关闭
    created_time: [] //创建时间
};

// 分组权限code码
const authCode = {
    add: 'GROUP_CHILD_ADD',
    edit: 'GROUP_EDIT',
    del: 'GROUP_DEL'
};

const handleGroupSubmit = (v: any) => {
    group_id.value = v.id;
    tableRef.value.clearSelection();
    // state.searchParams.group_id = v.id;
    state.searchParams = { ...deepCopy(state.searchParams), group_id: v.id };
};

// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const searchOption = computed(() => {
    return [
        {
            label: '门店搜索',
            name: 'search_value',
            value: '',
            type: 'input',
            placeholder: '请输入门店名称/门店地址'
        },
        {
            label: '创建人',
            name: 'created_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '门店状态',
            name: 'store_status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: -1 },
                            { name: '开启', id: 1 },
                            { name: '关闭', id: 2 }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: group_id.value
    };
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        group_id: group_id.value
    };
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const onBtn = (row: any) => {
    return (
        <>
            <ElButton
                v-show={row.store_status == 1}
                v-auth="OPEN"
                size="small"
                onClick={() => {
                    delId.value = [row.id];
                    onChange(1);
                }}>
                关店
            </ElButton>
            <ElButton
                v-show={row.store_status == 2}
                v-auth="OPEN"
                size="small"
                onClick={() => {
                    delId.value = [row.id];
                    onChange(2);
                }}>
                开店
            </ElButton>
            <ElButton
                size="small"
                v-auth="EDIT"
                onClick={() => {
                    router.push({
                        path: '/employee/storemanagement/storelist/detail',
                        query: { type: 'edit', id: row.id }
                    });
                }}>
                编辑
            </ElButton>
            <ElButton
                v-show={row.staff_num != 0}
                size="small"
                v-auth="DOWNLOAD"
                onClick={async () => {
                    delId.value = [row.id];
                    onChange(5);
                }}>
                下载
            </ElButton>
            <ElButton
                size="small"
                v-auth="MD_STAFF"
                onClick={() => {
                    StoreStaff(row);
                }}>
                门店员工
            </ElButton>
            <ElButton
                size="small"
                v-auth="DEL"
                onClick={() => {
                    delId.value = [row.id];
                    onChange(7);
                }}>
                删除
            </ElButton>
        </>
    );
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'words_name',
        label: '编码',
        width: 130,
        render({ row, column, index }) {
            return (
                <>
                    <div>{index + 1}</div>
                </>
            );
        }
    },
    {
        prop: 'store_name',
        label: '名称',
        width: 170,
        showOverflowTooltip: true
    },
    {
        prop: 'store_address',
        label: '地址',
        minWidth: 170,
        showOverflowTooltip: true
    },
    {
        prop: 'regional_area',
        label: '行政区域',
        minWidth: 170,
        showOverflowTooltip: true
    },
    {
        prop: 'group_name',
        label: '经纬度',
        width: 170,
        render({ row, column, index }) {
            return (
                <>
                    <div>
                        经度{row.lon},<br />
                        纬度{row.lat}
                    </div>
                </>
            );
        }
    },
    {
        prop: 'staff_num',
        label: '门店数员工',
        width: 120
    },
    {
        prop: 'group_name',
        label: '所属分组',
        width: 120
    },
    {
        prop: 'created_name',
        label: '创建人',
        width: 120
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 170
    },
    {
        prop: 'store_status',
        label: '营业状态',
        width: 120,
        render({ row, column, index }) {
            return (
                <>
                    <div v-show={row.store_status == 1} style="color: #60b900">
                        正常
                    </div>
                    <div v-show={row.store_status == 2} style="color: #969696">
                        关闭
                    </div>
                     
                    <div v-show={row.store_status == -1} style="color: #333333">
                        全部
                    </div>
                </>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    // 获取文件列表
    return getSensitivelist;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 导出表格数据
const exportTableData = () => {};
const onChange = (num: number) => {
    //1关店，2开店，3批量关店。4批量开店。5下载。6批量下载。7删除
    switch (num) {
        case 1:
            DeletdialogRef.value.appDialog.title = '关店提醒';
            DeletdialogRef.value.content = '确定关店吗？';
            break;
        case 2:
            DeletdialogRef.value.appDialog.title = '开店提醒';
            DeletdialogRef.value.content = '确定开店吗？';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '批量关店提醒';
            DeletdialogRef.value.content = '确定关店吗？';
            break;
        case 4:
            DeletdialogRef.value.appDialog.title = '批量开店提醒';
            DeletdialogRef.value.content = '确定开店吗？';
            break;
        case 5:
            DeletdialogRef.value.appDialog.title = '下载提醒';
            DeletdialogRef.value.content = '确定下载吗？';
            break;
        case 6:
            DeletdialogRef.value.appDialog.title = '批量下载提醒';
            DeletdialogRef.value.content = '确定下载所选内容吗？';
            break;
        case 7:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确定删除当前门店吗？';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    const params = delId.value.length ? delId.value : checkList.value;
    switch (
        isShow.value //1关店，2开店，3批量关店。4批量开店。5下载。6批量下载。7删除
    ) {
        case 1:
        case 3:
            startLoading();
            await getStogeChange1({ store_ids: params, type: 2 });
            ElMessage.success('关店成功');
            delId.value = [];
            checkList.value = [];
            tableRef.value.clearSelection();
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 2:
        case 4:
            startLoading();
            await getStogeChange1({ store_ids: params, type: 1 });
            ElMessage.success('开店成功');
            delId.value = [];
            checkList.value = [];
            tableRef.value.clearSelection();
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 5:
            // eslint-disable-next-line no-case-declarations
            const res2 = await getStogeDownload({ store_ids: params });
            downFile(res2.url, res2.name);
            ElMessage.success('下载成功');
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 6:
            // eslint-disable-next-line no-case-declarations
            const res = await getStogeDownload({ store_ids: params });
            downFile(res.url, res.name);
            // window.open(res.url)
            ElMessage.success('下载成功');
            delId.value = [];
            checkList.value = [];
            tableRef.value.clearSelection();
            DeletdialogRef.value.appDialog.visible = false;
            tableRef.value.reload();
            break;
        case 7:
            startLoading();
            await getStogeDel({ store_ids: params });
            ElMessage.success('删除成功');
            delId.value = [];
            checkList.value = [];
            tableRef.value.clearSelection();
            DeletdialogRef.value.appDialog.visible = false;
            GroupingRef.value.getGroup();
            tableRef.value.reload();
            break;
    }
};
// 导入门店
const ImportStore = (data: any) => {
    setTimeout(() => {
        ImportCustomerRef.value.appDialog.visible = true;
    }, 0);
};
const closeImportCustomer = () => {
    ImportCustomerRef.value.visible = false;
};
// 导入门店弹框-导入事件
const onImportCustomer = () => {
    tableRef.value.clearSelection();
};
//跳转新建门店
const getNewStore = () => {
    router.push({
        path: `/employee/storemanagement/storelist/detail`,
        query: { group_id: group_id.value }
    });
};
// 门店员工
const StoreStaff = (data: any) => {
    DetailedRef.value.width = 1000;
    DetailedRef.value.drawer = true;
    DetailedRef.value.isShow = false;
    DetailedRef.value.title = '门店员工';
    isShow.value = false;
    cus_import_id.value = data.id;
};
const showBox = () => {
    tableRef.value.reload();
};

onMounted(async () => {
    // const groupId = Number(route.query?.group_id);
    // if (groupId || groupId == 0) {
    //     if ((groupId || groupId == 0) && group_id.value != groupId) {
    //         group_id.value = groupId;
    //     } else {
    //         await GroupingRef.value.getGroup(22);
    //     }
    //     tableRef.value?.clearSelection();
    //     GroupingRef.value.setCurrentSelectId({ id: group_id.value });
    //     state.searchParams = {
    //         ...deepCopy(defaultParams),
    //         group_id: groupId || group_id.value
    //     };
    // }
});

onActivated(async () => {
    const groupId = Number(route.query?.group_id);
});
</script>

<style lang="scss" scoped>
.storelist_container {
    display: flex;

    .storelist_main {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}
</style>
